<template>
  <div
    class="flex flex-col flex-1"
    :class="{
      'overflow-y-auto': props.listData.height == 'flexMust',
      is_not_scrollbar: props.listData.data.length == 0,
    }"
    :ref="props.listData.id || 'tableFather'"
    :id="props.listData.id || 'tableFather'"
  >
    <!-- 头部按钮 -->
    <div class="flex flex-row h-32px aic mb-5px" v-if="props.listData.listBtns && props.listData.listBtns.length">
      <span v-if="selectData.length" class="text-primary mr-10px">已选{{ selectData.length }}条</span>
      <div class="flex flex-row">
        <template v-for="(item, index) in props.listData.listBtns" :key="index">
          <div
            @click="listClick(item)"
            v-if="item.type == 'btn'"
            pub:hover="bg-shallow "
            pub:border="hex-dcdfe6 1px"
            class="pl-15px pr-15px pt-4px pb-4px mr-10px cursor-pointer"
            :style="{ color: item.color, backgroundColor: item.backgroundColor, border: item.border }"
          >
            <span class="text-12px text-tableHeadertext" :style="{ color: item.color }">{{ item.title }}</span>
          </div>
          <div v-else-if="item.type == 'upload'">
            <a-upload
              name="file"
              :action="item.action"
              @change="item.handleChange"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel "
            >
              <div
                pub:hover="bg-shallow "
                pub:border="hex-dcdfe6 1px"
                class="pl-15px pr-15px pt-4px pb-4px mr-10px cursor-pointer"
                :style="{ color: item.color, backgroundColor: item.backgroundColor, border: item.border }"
              >
                <span class="text-12px text-tableHeadertext" :style="{ color: item.color }">{{ item.title }}</span>
              </div>
              <template #itemRender> </template>
            </a-upload>
          </div>
        </template>
      </div>
    </div>
    <!-- 表格内容 -->
    <a-table
      v-if="props.listShow"
      ref="table"
      class="ant-table-striped"
      :dataSource="props.listData.data"
      :columns="props.listData.columns"
      :scroll="scrollObj"
      :pagination="false"
      :rowKey="props.listData.rowKey || 'id'"
      @expand="expand"
      v-model:expandedRowKeys="props.listData.expandData"
      :row-selection="rowSelection"
    >
      <template #bodyCell="{ column, record, index }">
        <!-- 小数点后两位 -->
        <template v-if="column.type === 'twoDecimalPlaces'">
          <span>
            {{ Number(record[column.dataIndex]).toFixed(2) }}
          </span>
        </template>
        <!-- 小数点后两位 -->

        <!-- 序号 -->
        <template v-else-if="column.dataIndex === 'index'">
          <span>
            {{ index + 1 }}
          </span>
        </template>
        <!-- 序号 -->

        <!-- 操作 -->
        <template v-else-if="column.dataIndex === 'opt'">
          <div class="flex flex-row relative" v-if="optArr.length">
            <template v-for="(item, index) in optArr" :key="index">
              <div class="relative cursor-pointer" v-if="!item.noShow">
                <span
                  @click="optclick(item, record)"
                  :class="{ longString: index != optArr.length - 1 }"
                  class="mr-20px flex text-primary"
                  :style="{ color: item.color }"
                  >{{ item.title }}</span
                >
              </div>
            </template>
          </div>
        </template>
        <!-- 操作 -->

        <!-- 输入框 -->
        <template v-else-if="column.type === 'edit'">
          <div
            @click="cutEditTap(column, index)"
            v-if="!record['is_founs' + '_' + column.dataIndex]"
            class="border border-transparent"
            pub:hover="border border-primary rounded-5px"
          >
            {{ record[column.dataIndex] || '-' }}
          </div>
          <div v-else>
            <a-input
              :maxlength="20"
              :type="column.astrict || 'text'"
              :id="column.dataIndex + '_' + index"
              size="small"
              @pressEnter="cutEditBlur(column, record, index)"
              @blur="cutEditBlur(column, record, index)"
              v-model:value="record[column.dataIndex]"
            />
          </div>
        </template>
        <!-- 输入框 -->

        <!-- 自定义处理 -->

        <template v-else-if="column.type === 'custom'">
          <span v-diyValue="[record, column]"> </span>
        </template>
        <!-- 自定义处理 -->

        <template v-else>
          <span>
            {{ record[column.dataIndex] || '-' }}
          </span>
        </template>
      </template>
      <template #summary="{ pageData }" v-if="props.listData.summary && props.listData.data.length">
        <a-table-summary fixed>
          <a-table-summary-row>
            <a-table-summary-cell v-for="(item, index) in props.listData.columns" :key="index" :index="index">
              <div class="flex jcc aic" v-if="item.dataIndex == 'index'">
                {{ recursionFun(pageData, item.dataIndex, item.not_summary) }}
              </div>
              <div class="flex" v-else>{{ recursionFun(pageData, item.dataIndex, item.not_summary) }}</div>
            </a-table-summary-cell>
          </a-table-summary-row>
        </a-table-summary>
      </template>
      <!-- 子表单 -->
      <template #expandedRowRender="{ column, record, index }" v-if="props.listData.hasChild">
        <slot :column="column" :record="record" :index="index" name="down"></slot>
        <!-- 二级列表 -->
      </template>
    </a-table>
    <!-- 底部分页器 -->
    <div class="flex flex-row-reverse m-16px" v-if="props.listData.pagination">
      <a-pagination
        v-model:current="props.listData.page"
        v-model:pageSize="props.listData.pageSize"
        show-quick-jumper
        show-size-changer
        :total="props.listData.total || 50"
        @change="changePageSzie"
        :show-total="(total) => `共 ${total} 条`"
      >
      </a-pagination>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, onMounted, getCurrentInstance, watch, nextTick } from 'vue';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
const router = useRouter();
interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
}
const { proxy } = getCurrentInstance() as any;
const props = defineProps({
  listData: {
    type: Object,
    default: {},
  },
  listShow: {
    type: Boolean,
    default: true,
  },
});
interface scrollObj {
  y?: number;
  x?: number;
}
//可展示的表格行操作
let optArr = ref<Array<Object>>([]);
//控制宽高限制
let scrollObj = reactive<scrollObj>({});
//控制宽高限制

//编辑方法
const editClick = function (column: Object, row: Object, index: number, listID: string) {
  emit('editClick', column, row, index, listID);
};
//编辑方法
//操作方法
const optclick = function (item: Object, record: Object) {
  emit('optclick', item, record);
};
//操作方法
//表操作方法
const listClick = function (item: Object) {
  emit('listClick', item, selectData, props.listData.id);
};
//表操作方法

//判断父组件是需要自适应还是自动拉长还是固定宽度
if (typeof props.listData.height == 'number') {
  scrollObj.y = props.listData.height;
}
onMounted(() => {
  let isHasId = ref<Boolean>(false);
  if (props.listData.id) {
    isHasId.value = true;
  }
  //需要自适应高度
  if (props.listData.height == 'flex') {
    try {
      let summary = props.listData.summary; //是否需要合计
      let pagination = props.listData.pagination; //是否需要分页
      let listBtns = props.listData.listBtns; //是否表操作
      let comparison = 470; //极限值

      let calculate = isHasId
        ? proxy.$refs[props.listData.id].offsetHeight - 56
        : proxy.$refs.tableFather.offsetHeight - 56;
      scrollObj.x = isHasId
        ? proxy.$refs[props.listData.id].offsetWidth - 50
        : proxy.$refs.tableFather.offsetWidth - 50;
      if (summary) {
        calculate = calculate - 50;
        comparison = comparison - 50;
      }
      if (pagination) {
        calculate = calculate - 64;
        comparison = comparison - 64;
      }
      if (listBtns.length) {
        calculate = calculate - 32;
        comparison = comparison - 32;
      }
      if (calculate < comparison) {
        props.listData.height = 'auto';
      } else {
        props.listData.height = 'flexMust';
        scrollObj.y = calculate;
      }
    } catch (e) {
      //获取高度失败
    }
  } else if (props.listData.height == 'flexMust') {
    //不需要考虑小屏 强制自适应
    let calculate = isHasId
      ? proxy.$refs[props.listData.id].offsetHeight - 56
      : proxy.$refs.tableFather.offsetHeight - 56;
    scrollObj.x = isHasId ? proxy.$refs[props.listData.id].offsetWidth - 50 : proxy.$refs.tableFather.offsetWidth - 50;
    scrollObj.y = calculate;
  }
  //判断是不是子集
});
const recursionFun = function (data: Array<Object>, key: string, not_summary: boolean | undefined) {
  //data 数据源  key key值  not_summary 开启summary后默认全都计算 not_summary为true  代表当前不需要计算
  if (key == 'index') {
    return '合计';
  }
  if (not_summary) {
    return '';
  }
  let sums = 0;
  data.forEach((e: any, i) => {
    sums = sums + Number(e[key]);
  });
  return sums.toFixed(2);
};
//展开行操作
const expand = function (expanded: any, record: any) {
  emit('expand', expanded, record);
};
//展开行操作

//列表选择框
let rowSelection = reactive<any>(null);
let selectData = ref<any[]>([]);
if (props.listData.isRowSelection) {
  rowSelection = {
    onChange: function (selectedRowKeys: any[], selectedRows: DataType[]): void {
      selectData.value = selectedRowKeys;
    },
    getCheckboxProps: (record: DataType) => ({
      //选择框的默认属性配置
      disabled: false, // 不可选取
    }),
    selectedRowKeys: selectData,
  };
}
//列表选择框
//切换编辑转态
//选中
const storage = ref<string>(''); //存储上个值//存起来 以防修改失败
const cutEditTap = function (column: any, index: number) {
  storage.value = props.listData.data[index][column.dataIndex];
  props.listData.data[index]['is_founs' + '_' + column.dataIndex] = true;
  nextTick(() => {
    let editInputList: any = document.getElementById(column.dataIndex + '_' + index);
    editInputList.focus();
  });
};
//失去焦点
const cutEditBlur = function (column: any, row: any, index: number) {
  if (!props.listData.data[index]['is_founs' + '_' + column.dataIndex]) {
    return;
  }
  editClick(column, row, index, props.listData.id);
};
//切换编辑转态

//监听
watch(props, (val) => {
  //监听传值 并对列表的操作进行判断
  optArr.value = [];
  val.listData.optArr &&
    val.listData.optArr.forEach((e: any) => {
      if (!e.noShow) {
        optArr.value.push(e);
      }
    });
  if (props.listData.id == 'onlyId' && props.listData.data.length != 0) {
    //子集的id都是onlyId需要getdata的时候添加唯一健
    props.listData.id = props.listData.data[0].onlyId;
  }
});
watch(selectData, (val) => {
  emit('selectAll', props.listData.id, val);
});
//监听
//抛出方法给父级
const emit = defineEmits<{
  (e: 'changePageSzie', page: number, pageSize: number): void; //切换页面条数
  (e: 'expand', expanded: boolean, record: any): void; //切换页面条数
  (e: 'editClick', column: Object, row: Object, index: number, listID: string): void; //编辑方法
  (e: 'optclick', item: Object, record: Object): void; //操作方法
  (e: 'listClick', item: Object, selectData?: any, id?: string): void; //表操作方法
  (e: 'selectAll', id: string, arr: Array<string>): void; //选择框赋值给父列表统计用
}>();
//抛出方法给父级

//页数
const changePageSzie = function (page: number, pageSize: number) {
  emit('changePageSzie', page, pageSize);
};
//页数
</script>
<style scoped lang="less">
:deep(.ant-table-thead > tr > th) {
  background: @tableHeaderBgColor;
  color: @tableHeadertext;
  font-weight: 700;
  height: 48px;
  box-sizing: border-box;
  padding: 0px 16px;
}
:deep(.ant-table-cell) {
  &::before {
    display: none;
  }
}
:deep(.ant-table-tbody > tr > td) {
  padding: 13px 16px;
}
:deep(.ant-table-summary) {
  background: @tableHeaderBgColor;
  color: @tableHeadertext;
  font-weight: 700;
  height: 48px;
  box-sizing: border-box;
}

//表格滚动条
:deep(.ant-table-body) {
  overflow-x: hidden;
  &::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 5px;
    height: 1px;
  }

  &::-webkit-scrollbar-thumb {
    /*滚动条里面的滑块*/
    border-radius: 5px;
    background: #ebebeb;
  }

  &::-webkit-scrollbar-track {
    /*滚动条里面轨道背景*/
    border-radius: 5px;
    background: #fff;
  }
}
.is_not_scrollbar {
  :deep(.ant-table-container table > thead > tr:first-child th:last-child) {
    display: none;
  }
  :deep(.ant-table-body) {
    &::-webkit-scrollbar {
      /*滚动条整体样式*/
      width: 5px;
      height: 1px;
    }

    &::-webkit-scrollbar-thumb {
      /*滚动条里面的滑块*/
      border-radius: 5px;
      background: transparent;
    }

    &::-webkit-scrollbar-track {
      /*滚动条里面轨道背景*/
      border-radius: 5px;
      background: transparent;
    }
  }
}
.longString {
  &::before {
    position: absolute;
    width: 2px;
    height: 14px;
    background: #d6dbe3;
    content: '';
    right: 10px;
    top: 20%;
  }
}
</style>
